//
//  GetPictureFromDevice.m
//  WDFans
//
//  Created by Zhihong Yuan on 2/16/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GetPictureFromDevice.h"
#import "NSDate+Additions.h"

@implementation GetPictureFromDevice

@synthesize fileType = fileType_;
@synthesize fileName = fileName_;
@synthesize fileData = fileData_;
@synthesize delegate = delegate_;
@synthesize parentController;

- (void)dealloc
{
    [fileName_ release];
    [fileData_ release];
    [super dealloc];
}

- (id)initWithParentViewController:(id)pc
{
    if(self = [super init])
    {
        self.parentController = pc;
    }
    return  self;
}

#pragma mark - GetPictureFromDevice methods

- (void)takePhotoWithCamera
{
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; 
        ipc.sourceType =  UIImagePickerControllerSourceTypeCamera;
		if(fileType_ == kPhotoType)
			ipc.mediaTypes = [NSArray arrayWithObject:@"public.image"];
		else if(fileType_ == kMovieType){
			ipc.mediaTypes = [NSArray arrayWithObject:@"public.movie"];
		}
        else
        {
            ipc.mediaTypes = [NSArray arrayWithObjects:@"public.image",@"public.movie", nil];
        }
        //ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];   
		ipc.delegate = self; 
		ipc.allowsEditing = NO; 
        //if([self.parentController respondsToSelector:@selector(presentModalViewController:animated:)])
        [(UIViewController *)self.parentController presentModalViewController:ipc animated:YES];
		[ipc release];
	} 
	else {
        [delegate_ didGetFileFailedWithMessage:@"设备不支持摄像头"];
	}
}

- (void)getPhotoFromLibrary
{
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
	{
		UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary; 
		if(fileType_ == kPhotoType)
			ipc.mediaTypes = [NSArray arrayWithObject:@"public.image"];
		else if(fileType_ == kMovieType){
			ipc.mediaTypes = [NSArray arrayWithObject:@"public.movie"];
		}
        else
        {
            ipc.mediaTypes = [NSArray arrayWithObjects:@"public.image",@"public.movie", nil];
        }
        //ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];   
		ipc.delegate = self; 
		ipc.allowsEditing = NO; 
        //if([self.parentController respondsToSelector:@selector(presentModalViewController:animated:)])
        [(UIViewController *)self.parentController presentModalViewController:ipc animated:YES];
		[ipc release];
	} 
	else {
        [delegate_ didGetFileFailedWithMessage:@"设备不支持摄像头"];
	}
}

#pragma mark UIImagePickerController delegate methods
//Get thumbnail image for movie the user choose to show in pre-view
//- (UIImage *)getThumbnailImageForMovie:(UIImagePickerController *)imagePicker
//{
//	//CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
//	CGSize sixzevid=CGSizeMake(imagePicker.view.bounds.size.width,imagePicker.view.bounds.size.height-100);
//	UIGraphicsBeginImageContext(sixzevid);
//	[imagePicker.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
//	UIGraphicsEndImageContext();
//	return viewImage;
//}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	NSString *fullName = nil;
	NSData *uploadData = nil;
	//NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; 
	if(fileType_ == kPhotoType){
        //if ([mediaType isEqualToString:@"public.image"]){ 
		UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; 
		NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
		if(url != nil)
		{
			NSString *path = [NSString stringWithFormat:@"%@",url];
			NSFileManager *fm = [[NSFileManager alloc] init];
			NSString *name = [fm displayNameAtPath:path];
			[fm release];
			NSArray *sepArray = [name componentsSeparatedByString:@"?"];
			NSString *fileNameAndFix = [sepArray objectAtIndex:1];
			NSArray *sepArray1 = [fileNameAndFix componentsSeparatedByString:@"&"];
			NSString *fileName = [[[sepArray1 objectAtIndex:0] componentsSeparatedByString:@"="] objectAtIndex:1];
			NSString *filefix = [[[sepArray1 objectAtIndex:1] componentsSeparatedByString:@"="] objectAtIndex:1];
			fullName = [NSString stringWithFormat:@"%@.%@",fileName,filefix];
			if([filefix isEqualToString:@"PNG"])
			{
				uploadData = UIImagePNGRepresentation(image);
			}
			else {
				uploadData = UIImageJPEGRepresentation(image, 0.5);
			}
		}
		else {
			NSString *str = [NSDate dateToStringByFormat:[NSDate date] format:@"yyyyMMddHHmmss"];
			fullName = [NSString stringWithFormat:@"%@takephoto.jpg",str];
			uploadData = UIImageJPEGRepresentation(image, 0.5);
		}
	} 
	else if(fileType_ == kMovieType){
		NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; 
		uploadData = [NSData dataWithContentsOfURL:videoURL]; 
		NSString *path = [NSString stringWithFormat:@"%@",videoURL];
		if(path != nil)
		{
			NSFileManager *fm = [[NSFileManager alloc] init];
			fullName = [fm displayNameAtPath:path];
			//fullname:trim.***.mov
			fullName = [fullName substringFromIndex:5];
			[fm release];
		}
		else {
            NSString *str = [NSDate dateToStringByFormat:[NSDate date] format:@"yyyyMMddHHmmss"];
			fullName = [NSString stringWithFormat:@"%@takevideo.mov",str];
		}
        //get thumbnail image for movie, set if needed.
		//UIImage *img = [self getThumbnailImageForMovie:picker];
		//NSData *d = UIImagePNGRepresentation(img);
	}
    NSLog(@"image full name is:%@",fullName);
	// Setting up the URL to post to
	self.fileName = fullName;
	self.fileData = uploadData;
    [delegate_ didGetFileWithData:self.fileData andName:self.fileName];
	[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[picker dismissModalViewControllerAnimated:YES];
}
@end
